package com.tougutips.cookbook.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.common.core.domain.R;
import com.tougutips.cookbook.dto.NewCookbookDto;
import com.tougutips.cookbook.entity.Cookbook;
import com.tougutips.cookbook.entity.CookbookMaterial;
import com.tougutips.cookbook.entity.CookbookStep;
import com.tougutips.cookbook.entity.Material;
import com.tougutips.cookbook.mapper.CookbookMapper;
import com.tougutips.cookbook.mapper.CookbookMaterialMapper;
import com.tougutips.cookbook.mapper.CookbookStepMapper;
import com.tougutips.cookbook.mapper.MaterialMapper;
import com.tougutips.cookbook.service.CookbookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author jun
* @description 针对表【cookbook】的数据库操作Service实现
* @createDate 2022-07-21 11:43:32
 * todo: 热量计算方法
*/
@Slf4j
@Service
public class CookbookServiceImpl extends ServiceImpl<CookbookMapper, Cookbook>
    implements CookbookService {

    @Autowired(required = false)
    private CookbookMapper cookbookMapper;

    @Autowired(required = false)
    private CookbookMaterialMapper cookbookMaterialMapper;

    @Autowired(required = false)
    private CookbookStepMapper cookbookStepMapper;


    /**
     *新增菜谱业务
     */
    @Override
    @Transactional
    public R addCookbook(NewCookbookDto newCookbookDto) {
        // 获得菜单信息
        Cookbook cookbook = newCookbookDto.getCookbook();
        // 操作时长计算
        Integer cookbookTime = 0;
        // 获取食材
        List<CookbookMaterial> cookbookMaterials = newCookbookDto.getCookbookMaterials();
        //操作时长汇总
        List<CookbookStep> cookbookSteps = newCookbookDto.getCookbookSteps();
        for (CookbookStep cookbookStep : cookbookSteps) {
            cookbookTime += Integer.parseInt(cookbookStep.getStepTime());
        }
        //设置时长
        cookbook.setCookbookTime(cookbookTime.toString());
        //插入菜谱表
        cookbookMapper.insert(cookbook);
        // 获得插入后的唯一id
        Long id = cookbook.getId();
        // 如果id为null，则插入失败
        if (id == null) return R.fail();
        //插入食材信息
        for (CookbookMaterial material : cookbookMaterials) {
            material.setCookbookId(id);
            cookbookMaterialMapper.insert(material);
        }
        //插入步骤信息
        for (CookbookStep cookbookStep : cookbookSteps){
            cookbookStep.setCookbookId(id);
            cookbookStepMapper.insert(cookbookStep);
        }

        return R.ok();
    }


}




